package src.jus.aor.mobilagent.kernel;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.jar.JarException;

public class BAMLoader extends URLClassLoader{
	
	private Map<String,byte[]> classmap = new HashMap<String,byte[]>();
	Jar jarfile;
	
	public BAMLoader(){
		super(new URL[]{},null);
	}
	public BAMLoader(ClassLoader loader){
		super(new URL[]{},loader);
		classmap=new HashMap<String, byte[]>();
	}
	public void addURL(String jar) {
		try {
			jarfile = new Jar(jar);
			integrateCode(jarfile);
			super.addURL(new URL("file:/"+jar));
		} catch (JarException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		   }
		}
	public Jar extractCode(){
			return jarfile;		
		}
		
	@Override
	public Class<?> findClass(String className) throws ClassNotFoundException {
		Class<?> result = null;  
		byte classByte[]; 	
		if(classmap.containsKey(className)){
			classByte = classmap.get(className);
		//	System.err.println("nom"+className);
			result = defineClass(className, classByte, 0, classByte.length);
			return result;
		}
		else throw new ClassNotFoundException(className);
			
	}
	public void integrateCode(Jar jar) {
		// TODO Auto-generated method stub
		jarfile = jar;
		String nomClass;
		byte[] code ;
		Entry<String,byte[]> valeur;
		Iterable<Entry<String, byte[]>> tmp = jar.classIterator();
		Iterator<Entry<String, byte[]>> it = tmp.iterator();
		while(it.hasNext()){
			valeur = it.next();
			nomClass = valeur.getKey();
			code = valeur.getValue();
			classmap.put(jar.formatClassName(nomClass), code);
		}			
			
	}

	public void print() {
		String nomClass;
		Entry<String,byte[]> valeur;
		Iterable<Entry<String, byte[]>> tmp = jarfile.classIterator();
		Iterator<Entry<String, byte[]>> it = tmp.iterator();
		while(it.hasNext()){
		valeur = it.next();
			nomClass = valeur.getKey();
			System.err.println(jarfile.formatClassName(nomClass));
		}		
			
	}
}
